// npm install redis
const redis = require('redis');

// 读取连接 Redis 的配置
const config = require('../util/server_config');
const { host, port, pswd } = config.redis;

let url = `redis://:${pswd}@${host}:${port}`

let redisClient = {
    initRedis,
    client: null,
    set,
    get
};

function initRedis() {
    // 限制 redisClient.client 只初始化一次
    if (redisClient.client) { return };
    return new Promise((resolve, reject) => {
        console.log('正在连接 Redis 数据库 ...', host, port, pswd);
        // 创建 Redis 客户端
        let client = redis.createClient({ url });
        // let client = redis.createClient({
        //     host: host,
        //     port: port,
        //     password: pswd
        // });
        client.on('connect', () => {
            console.log('Redis 连接成功 ! ! !');
            redisClient.client = client;
            resolve("Redis 连接成功 ! ! !");
        });
        client.on('error', (err) => {
            console.error('Redis 连接失败:', err);
            reject("Redis 连接失败 ! ! !");
            process.exit(1);
        });
        client.connect();
    });
}

async function set(key, value, expiry) {
    if (!redisClient.client) {
        throw new Error('Redis client not initialized');
    }
    await redisClient.client.set(key, value);
    await redisClient.client.expire(key, expiry);
}

async function get(key) {
    if (!redisClient.client) {
        throw new Error('Redis client not initialized');
    }
    return await redisClient.client.get(key);
}

module.exports = redisClient;